const express = require('express')
const router = express.Router()
const User = require('../models/user')
const Userinfo = require('../models/userInfo')
const models = require('../models')
const session = require('express-session')
const { Op } = require('sequelize')
const request = require('request')

const fs = require('fs')

const AipImageClassifyClient = require('baidu-aip-sdk').imageClassify

// baidu ai get the access_token for car detect ----start
const APP_ID = '19958093'
const API_KEY = 'IGRhjx3YfzadBfr3zjpgWXy2'
const SECRET_KEY = 'E1jEkfOt263Rc5gYI3AoehndE4ZAyvRg'
const client = new AipImageClassifyClient(APP_ID, API_KEY, SECRET_KEY)
// baidu ai get the access_token for car detect ----end

router.get('/login', (req, res) => {
  res.render('index.html')
})

router.post('/login', async (req, res, next) => {
  //查询usrs表中的所有数据

  await models.User.findAll({
    where: {
      [Op.and]: [
        { username: req.body.username },
        { password: req.body.password },
      ],
    },
  }).then((users) => {
    if (users.length != 0) {
      req.session.user = req.body.username
      res.send({
        code: 200,
        msg: '登陆成功',
      })
    } else {
      return res.send({
        code: -1,
        msg: '用户名或则密码错误',
      })
    }
  })
})

router.get('/dashbord', (req, res) => {
  if (req.session.user) {
    res.render('dashbord.html', { username: req.session.user })
  } else {
    res.redirect('/login')
  }
})
router.get('/logout', (req, res) => {
  req.session.user = null
  res.redirect('/login')
})

router.get('/car-owner', async (req, res) => {
  res.render('car-owner.html')
})
router.get('/car-owner-add', (req, res) => {
  res.render('car-owner-add.html')
})

router.post('/api/userinfo/add', async (req, res) => {
  await models.Userinfo.create({
    userid: req.body.userid,
    car_info: req.body.car_info,
    img_url: req.body.img_url,
    car_color: req.body.car_color,
    createdAt: new Date(),
  }).then((ret) => {
    res.json({
      code: 201,
      msg: '车主新增成功',
    })
  })
})

//==================== all user routers starts ====================

router.get('/user-list', async (req, res) => {
  const size = 5
  const page = 1
  let users = await models.User.findAll({
    attributes: {
      excludse: ['password'],
    },
    offset: (page - 1) * size,
    limit: size,
    order: [['id', 'DESC']],
  })
  // res.json({ users: users })
  res.render('user-list.html', { users: JSON.parse(JSON.stringify(users)) })
})

router.get('/user-add', (req, res) => {
  res.render('user-add.html')
})

router.get('/user-edit', (req, res) => {
  res.render('user-edit.html')
})

router.get('/user-password', (req, res) => {
  res.render('user-password.html')
})

router.get('/api/userinfo', async (req, res) => {
  await models.Userinfo.findAll({
    attributes: [
      'id',
      'userid',
      'car_info',
      'car_license',
      'car_color',
      'img_url',
      'createdAt',
    ],
  }).then((ret) => {
    res.json({
      code: 0,
      data: ret,
    })
  })
})

//==================== all user routers ends ====================

//==================== all api routers starts ====================-

router.get('/api/users', async (req, res) => {
  const size = parseInt(req.query.curr) || 1
  const page = parseInt(req.query.nums) || 5

  const users = await models.User.findAll({
    attributes: ['id', 'username', 'email', 'is_admin', 'status', 'createdAt'],
    offset: size * (size - 1),
    limit: page,
  })
  res.json({
    code: 0,
    data: users,
  })
})

router.post('/api/user/add', async (req, res) => {
  // console.log(req.body)
  const users = await models.User.create({
    email: req.body.email,
    username: req.body.username,
    password: req.body.pass,
    is_admin: 0,
    status: 1,
    createdAt: new Date(),
    updatedAt: new Date(),
  })
  res.json({
    code: 201,
    msg: '用户增加成功',
  })
})

// router.post('/api/user/del/:id', async (req, res) => {
//   // console.log(req.body)
//   const users = await models.User.destroy({
//     where: {
//       userid: req.params.userid,
//     },
//   })
//   res.json({
//     code: 201,
//     msg: '用户删除成功',
//   })
// })

router.put('/api/user/status/:id', async (req, res) => {
  // console.log(req.body.status)
  const s = await models.User.findOne({ where: { id: req.params.id } }).then(
    (ctx) => {
      if (ctx) {
        ctx.update({
          status: !res.status,
        })
        res.json({
          code: 204,
          msg: '用户状态更新成功',
        })
      }
    }
  )
})
router.delete('/api/user/delete/:id', async (req, res) => {
  // const user = await models.User.findOne({ where: { id: req.params.id } })
  // if (user.is_admin == true) {
  // return false
  // }
  await models.User.destroy({
    where: {
      id: req.params.id,
      [Op.and]: [{ is_admin: false }],
    },
  }).then((ret) => {
    res.json({
      msg: 'ok',
    })
  })
})
router.post('/api/user/login', async (req, res) => {
  await models.User.findAll({
    attributes: { exclude: ['password', 'is_admin', 'status'] },
    where: {
      [Op.and]: [{ email: req.body.email }, { password: req.body.password }],
    },
  }).then((users) => {
    if (users.length != 0) {
      res.json({
        code: 200,
        msg: '登陆成功',
        user: users,
      })
    } else {
      return res.json({
        code: -1,
        msg: '用户名或则密码错误',
      })
    }
  })
})

router.post('/api/user/register', async (req, res) => {
  const users = await models.User.create({
    email: req.body.email,
    username: req.body.username,
    password: req.body.password,
    is_admin: 0,
    status: 1,
    createdAt: new Date(),
    updatedAt: new Date(),
  })
  if (users) {
    res.json({
      code: 201,
      msg: '用户增加成功',
    })
  } else {
    res.json({
      code: -1,
      msg: '用户已存在',
    })
  }
})

router.get('/api/userinfo/:id', async (req, res) => {
  const a = models.Userinfo
  console.log(a)
})

router.post('/api/userinfo/:userid', async (req, res) => {
  await models.Userinfo.findAll({
    attributes: [
      'id',
      'userid',
      'img_url',
      'car_color',
      'car_info',
      'car_license',
    ],
    where: {
      userid: {
        [Op.eq]: req.params.userid,
      },
    },
  }).then((userinfo) => {
    //console.log(JSON.stringify(users));
    if (userinfo.length != 0) {
      //req.session.user = JSON.parse(JSON.stringify(users))[0].username
      const user = JSON.parse(JSON.stringify(userinfo))
      console.log(userinfo)

      // req.session.user = req.body.username
      // console.log(req.session.user)

      res.send({
        code: 200,
        msg: '登陆成功',
        user: JSON.parse(JSON.stringify(userinfo)),
      })
    } else {
      return res.send({
        code: -1,
        msg: '邮箱或密码错误',
      })
    }
  })
})

router.post('/api/car/:img_url', async (req, res) => {
  const image_url = req.body.img_url

  console.log(image_url)

  // const imageBuffer = request(image_url, (err, res, buffer) => {
  // if (!err && res.statusCode == 200) {
  // console.log(buffer.toString('base64'))
  // return buffer.toString('base64')
  // }
  // })
  request(image_url, { encoding: null }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      data = Buffer.from(body, 'utf-8').toString('base64')
      // 'data:' +
      // response.headers['content-type'] +
      // ';base64,' +
      // Buffer.from(body, 'utf-8').toString('base64')

      client
        .carDetect(data)
        .then(function (ret) {
          if (!ret.error_msg) {
            res.json({
              data: JSON.stringify(ret),
            })
          } else {
            res.json({
              data: ret.error_msg,
            })
          }
        })
        .catch(function (err) {
          console.log(err)
        })
    }
  })

  // console.log(req.params.img_url)
})

router.post('/api/query/:license', async (req, res) => {
  console.log(req.body.query)
  const query = req.body.query
  await models.Userinfo.findAll({
    attributes: [
      'id',
      'userid',
      'img_url',
      'car_color',
      'car_info',
      'car_license',
    ],
    where: {
      car_info: {
        [Op.like]: `%${query}%`,
      },
    },
    // offset: 10,
    // limit: 2,
  })
    .then((ret) => {
      console.log(ret)
      if (ret != '') {
        res.json({
          cars: JSON.stringify(ret),
        })
      } else {
        res.json({
          msg: '没有此数据',
        })
      }
    })
    .then((err) => {
      console.log(err)
    })
})

router.post('/api/catCheck/:access_token', async (req, res) => {
  config = {
    token:
      '24.a86d391293e89e2557c222038524d309.2592000.1592486604.282335-19958093',
    url:
      'https://aip.baidubce.com/rest/2.0/image-classify/v1/car?access_token=' +
      $token,
  }
  req = request
})
module.exports = router
